package wei.xinya.minio.controller;

import com.alibaba.fastjson.JSONArray;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/minio")
public class MinioController {
    @Resource
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    @GetMapping("/list")
    public List<String> list() {
        List<String> names = new ArrayList<>();

        Iterable<Result<Item>> results = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());

        try {
            for (Result<Item> itemResult : results) {
                names.add(itemResult.get().objectName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return names;
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file") List<MultipartFile> fileList) {
        try {
            // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!isExist) {
                // 创建存储桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        fileList.parallelStream().forEach(file -> {
            try {
                String fileName = file.getOriginalFilename();
                System.out.println("start upload " + fileName);

                InputStream inputStream = file.getInputStream();
                PutObjectArgs putObjectArgs = PutObjectArgs.builder().bucket(bucketName).object(fileName)
                        .stream(inputStream, inputStream.available(), -1).build();

                // 使用putObject上传一个文件到存储桶中。
                minioClient.putObject(putObjectArgs);
                inputStream.close();

                String objectUrl = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET).bucket(bucketName).object(fileName).build());

                System.out.println("successfully upload " + objectUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        return "successfully uploaded " + fileList.size() + " file";
    }

    @PostMapping("/delete")
    public String delete(@RequestBody JSONArray array) {
        if (array.isEmpty()) {
            return "file is empty";
        }

        List<String> strings = array.toJavaList(String.class);
        strings.parallelStream().forEach(file -> {
            try {
                minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(file).build());
                System.out.println("delete " + file);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        return "delete " + array.size() + " file success";
    }

}
